﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Xna.Framework;

namespace TD.TheGame
{
    public class AnimationHandler
    {
        public Rectangle[] animationRec(string uri)
        {
            // The file does not exists. (NOTE: Hotfix)
            if (!File.Exists(uri))
                return new Rectangle[1] { Rectangle.Empty };

            Debug.WriteLine("Loading XML data: " + uri);

            try
            {
                Rectangle[] animationRec;
                //init die array
                XElement xelementDie = XElement.Load(uri);

                // Read the entire XML
                var rectangles = from rectangle in xelementDie.Descendants("frame")
                                 select new
                                 {
                                     X = rectangle.Element("layers").Element("layer").Element("rect").Attribute("x"),
                                     Y = rectangle.Element("layers").Element("layer").Element("rect").Attribute("y"),
                                     W = rectangle.Element("layers").Element("layer").Element("rect").Attribute("width"),
                                     H = rectangle.Element("layers").Element("layer").Element("rect").Attribute("height")
                                 };

                animationRec = new Rectangle[rectangles.Count()];
                int countRec = 0;
                foreach (var rectangle in rectangles)
                {
                    animationRec[countRec] = new Rectangle((int)rectangle.X, (int)rectangle.Y, (int)rectangle.W, (int)rectangle.H);
                    countRec++;
                }
                return animationRec;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("AnimationHandler::animationRec ==> " + ex.GetType().ToString() + ": " + ex.Message);
                return new Rectangle[1] { Rectangle.Empty };
            }
        }
    }
}
